package qq2564874169.tuaotuao.fx.concurrent;

import qq2564874169.tuaotuao.fx.utils.ExUtil;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class FxCountDownLatch extends CountDownLatch {

    private Exception ex;

    public Exception getError() {
        return ex;
    }

    public void countDown(Exception ex) {
        super.countDown();
        this.ex = ex;
    }

    @Override
    public void await() {
        try {
            super.await();
        } catch (InterruptedException e) {
            ex = e;
        }
        if (ex != null) {
            throw ExUtil.toRuntime(ex);
        }
    }

    @Override
    public boolean await(long timeout, TimeUnit unit) {
        boolean rs;
        try {
            rs = super.await(timeout, unit);
        } catch (InterruptedException e) {
            ex = e;
            rs = getCount() == 0;
        }
        if (ex != null) {
            throw ExUtil.toRuntime(ex);
        } else {
            return rs;
        }
    }

    public FxCountDownLatch() {
        super(1);
    }

    /**
     * Constructs a {@code CountDownLatch} initialized with the given count.
     *
     * @param count the number of times {@link #countDown} must be invoked
     *              before threads can pass through {@link #await}
     * @throws IllegalArgumentException if {@code count} is negative
     */
    public FxCountDownLatch(int count) {
        super(count);
    }
}
